﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Achievement.BLL.Provider;
using Achievement.DataModels;
using System.Text;
using Achievement.Web.Common;
using Achievement.Common;
using Ebooom.Leads.Business.AuthorRole;
using System.Configuration;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;

namespace Achievement.Web.Controllers
{
    [Authorize]
    public class AchievementController : Controller
    {
        //
        // GET: /Achievement/

        public ActionResult Index()
        {
            List<VFolder> mylist = FolderProvider.Instance.GetVFolders();
            string str = string.Empty;
            GetMcDropdown(0, null, mylist, ref str);
            ViewData["ddlParent"] = str;

            List<string> aTypes = FolderProvider.Instance.GetAchievementsType();
            ViewData["ddlType"] = from t in aTypes select new SelectListItem() { Text = t, Value = t };
            return View();
        }

        public ActionResult GetAchievementList()
        {

            return View();
        }

        public ActionResult list(string where, long? folder,string type, int page, int rows, string sord, string sidx)
        {
            int totalRecords = 0;
            where = " and (a.ProjectName like '%" + where + "%' or KeyWord like '%" + where + "%')";
            if (!UserInfo.ValidataRole(1))
            {
                where += " and IsActive=1";
            }
            var mylist = AchievementsProvider.Instance.GetAchievementsList(where,folder.SecureToLong(),type, page, rows, sord, sidx, out totalRecords);
            var folderlist = AchievementsProvider.Instance.GetFolderList();
            var json = new
            {
                total = (int)Math.Ceiling((double)totalRecords / rows),
                page = page,
                records = totalRecords,
                rows = from c in mylist
                       select new
                       {
                           id = c.ID,
                           cell = new[] { c.ID.ToString(), c.ProjectName, c.KeyWord, c.Participant, c.Type, GetFolderName(c.Folder,folderlist), c.Desc, c.CreateTime.ToString(),
                               (UserInfo.ValidataRole(4)?"<a href=\"/Achievement/Download?ids=" + c.ID + "\" target=\"_blank\">下载</a>":"") +
                                (UserInfo.ValidataRole(8)?"&nbsp;&nbsp;<a href=\"/Achievement/View?id=" + c.ID + "\">预览</a>":"") +
                                (UserInfo.ValidataRole(1)? "&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"$.facebox({ ajax: '/Achievement/UploadFile?id=" + c.ID + "'})\">修改</a>" +
                                "&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"deleteacmt(" + c.ID + ")\">删除</a>":"") + 
                                (!c.IsActive? "&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"AchievementAuditing(" + c.ID + ")\">审核通过</a>":"")
                           }
                       }
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        public string Operate()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<a href=''>替换</a>&nbsp;&nbsp;");
            sb.Append("<a href=''>下载</a>");
            return sb.ToString();

        }

        public string GetTypeName(int? type)
        {
            string name = "无";
            switch(type)
            {
                case 1:
                    name = "wrod";
                    break;
                case 2:
                    name = "excel";
                    break;
                case 3:
                    name = "ppt";
                    break;
                case 4:
                    name = "flv";
                    break;
                case 5:
                    name = "pdf";
                    break;
            }
            return name;
        }

        public string GetFolderName(long? fId,List<Folder> list)
        {
            if (fId != null)
            {
                var folder = (from f in list where f.ID == fId select f).FirstOrDefault();
                return folder.Name;
            }
            return null;
        }

        public ActionResult UploadFile(long? id)
        {
            var myFolders = FolderProvider.Instance.GetFidsByUid(UserInfo.CurrentUser.ID);
            List<VFolder> mylist = FolderProvider.Instance.GetVFolderTreeByIds(myFolders);
            string str = string.Empty;
            GetMcDropdown(0, null, mylist, ref str);
            ViewData["ddlParent"] = str;
            Achievements acmt = new Achievements();
            if (id != null)
            {
                acmt = AchievementsProvider.Instance.GetAchievementById(id.SecureToLong());
            }
            else
            {
                acmt.Folder = mylist[0].ID;
            }
            return View(acmt);
        }

        [HttpPost]
        public ActionResult Upload(Achievements acmt, long category)
        {
            string[] imageType = ConfigurationManager.AppSettings["ImageType"].Split(',');
            string[] officType = ConfigurationManager.AppSettings["OfficeType"].Split(',');
            string[] pdfType = ConfigurationManager.AppSettings["PdfType"].Split(',');
            string[] mediaType = ConfigurationManager.AppSettings["MediaType"].Split(',');
            if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
            {
                HttpPostedFileBase file = Request.Files[0];
                string fileExtension = string.Empty;
                if (file.ContentLength > UserInfo.CurrentUser.UploadSize.SecureToLong() * 1024 * 1024)
                {
                    return Content(ATools.OperateAlter("上传大小超过管理员制定限制！", "/achievement"));
                }
                string fileName = CommonTools.UploadFile(file, out fileExtension);
                acmt.UploadFile = fileName;
                fileExtension = fileExtension.Substring(1);
                if (imageType.Contains(fileExtension))
                {
                    acmt.DisplayFilePath = fileName;
                }
                else if (officType.Contains(fileExtension))
                {
                    string pdfFileName = CommonTools.UploadOffice2Pdf(fileName);
                    string saveName = CommonTools.UploadPdf2Swf(pdfFileName);
                    acmt.DisplayFilePath = saveName;
                }
                else if (pdfType.Contains(fileExtension))
                {
                    string saveName = CommonTools.UploadPdf2Swf(fileName);
                    acmt.DisplayFilePath = saveName;
                }
                else if (mediaType.Contains(fileExtension))
                {
                    acmt.DisplayFilePath = fileName;
                }
                else
                {
                    return Content(ATools.OperateAlter("上传文件格式不正确！", "/achievement"));
                }
                acmt.Type = fileExtension;
            }
            if (acmt.ID > 0)
            {
                Achievements saveA = AchievementsProvider.Instance.GetAchievementById(acmt.ID);
                saveA.Owner = UserInfo.CurrentUser.ID;
                saveA.Folder = category;
                saveA.Desc = acmt.Desc;
                saveA.KeyWord = acmt.KeyWord;
                saveA.Participant = acmt.Participant;
                saveA.ProjectName = acmt.ProjectName;
                if (!string.IsNullOrEmpty(acmt.Type)) saveA.Type = acmt.Type;
                if (!string.IsNullOrEmpty(acmt.UploadFile)) saveA.UploadFile = acmt.UploadFile;
                if (!string.IsNullOrEmpty(acmt.DisplayFilePath)) saveA.DisplayFilePath = acmt.DisplayFilePath;
                AchievementsProvider.Instance.SaveAchievement(saveA);
            }
            else
            {
                acmt.CreateTime = DateTime.Now;
                acmt.Owner = UserInfo.CurrentUser.ID;
                acmt.Folder = category;
                AchievementsProvider.Instance.AddAchievement(acmt);
            }
            return Content(ATools.OperateAlter("操作成功！", "/achievement"));
        }

        [AuthorizeFilter(ValidataRole = 8)]
        public ActionResult View(long id)
        {
            if (id > 0)
            {
                Achievements a = AchievementsProvider.Instance.GetAchievementById(id);
                if (a != null)
                {
                    AchievementsProvider.Instance.UpdateCount(id);
                    return View(a);
                }
            }
            return Content(CommonTools.OperateAlter("内容不存在！", "/achievement"));
            
        }

        public ActionResult CommentList(long id, int page, int rows, string sord, string sidx)
        {
            int totalRecords = 0;
            
            var mylist = AchievementsProvider.Instance.GetVCommentList(id, page, rows, sord, sidx, out totalRecords);
            var json = new
            {
                total = (int)Math.Ceiling((double)totalRecords / rows),
                page = page,
                records = totalRecords,
                rows = from c in mylist
                       select new
                       {
                           id = c.CID,
                           cell = new[] { c.CID.ToString(), c.AID.ToString(), c.UID.ToString(), c.Score.ToString(), c.Content, c.CreateTime.ToString("yyyy-MM-dd"), c.Name, c.Image }
                       }
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult AddComment(long id, string txtComment, int txtScore)
        {
            Comment c = new Comment();
            c.AID = id;
            c.UID = UserInfo.CurrentUser.ID;
            c.Score = txtScore;
            c.CreateTime = DateTime.Now;
            c.Content = txtComment;
            AchievementsProvider.Instance.AddComment(c);
            return Content(ATools.OperateAlter("操作成功！", "/Achievement/view?id=" + id.ToString()));
        }

        [HttpGet]
        public ActionResult EditComment(long id)
        {
            Comment c = new Comment();
            if (id > 0)
            {
                c = AchievementsProvider.Instance.GetCommentById(id) ?? new Comment();
            }
            return View(c);
        }

        [HttpPost]
        public ActionResult EditComment(Comment c)
        {
            Comment save = AchievementsProvider.Instance.GetCommentById(c.CID);
            save.Content = c.Content;
            save.Score = c.Score;
            AchievementsProvider.Instance.EidtComment(save);
            return Content(ATools.OperateAlter("操作成功！", "/Achievement/view?id=" + c.CID.ToString()));
        }

        public ActionResult DeleteComment(long id, long aid)
        {
            AchievementsProvider.Instance.DeleteComment(id);
            return Content(ATools.OperateAlter("操作成功！", "/Achievement/view?id=" + aid.ToString()));
        }

        public void GetMcDropdown(int level, VFolder folder, List<VFolder> list, ref string str)
        {
            List<VFolder> query = null;
            List<long?> ids = list.Select(f => (long?)f.ID).ToList();
            if (folder == null)
            {
                query = list.Where(l => !ids.Contains(l.Parent)).ToList();
            }
            else
            {
                query = list.Where(l => l.Parent == folder.ID).ToList();
            }
            foreach (var item in query)
            {
                if (item.SunCount > 0)
                {

                    str += string.Format("<li rel=\"{0}\">{1}\r\n<ul>\r\n", item.ID, item.Name);
                    GetMcDropdown(level + 1, item, list, ref str);
                    str += "</ul>\r\n</li>\r\n";
                }
                else
                {
                    str += string.Format("<li rel=\"{0}\">{1}</li>\r\n", item.ID, item.Name);
                }

            }
        }

        public ActionResult Delete(long id)
        {
            AchievementsProvider.Instance.DeleteAchievementById(id);
            return Content(ATools.OperateAlter("操作成功！", "/Achievement"));
        }

        public ActionResult Download(string ids)
        {
            if (!string.IsNullOrEmpty(ids))
            {
                List<long> sIds = new List<string>(ids.Split(',')).ConvertAll(i => i.SecureToLong());
                if (sIds.Count == 1)
                {
                    Achievements a = AchievementsProvider.Instance.GetAchievementById(sIds[0]);
                    return File(ConfigurationManager.AppSettings["SavePath"] + a.UploadFile, "application/octet-stream", a.UploadFile);
                }
                if (sIds.Count > 1)
                {
                    List<Achievements> list = AchievementsProvider.Instance.GetAchievementByIds(sIds.ToArray());
                    string tempFolder = Server.MapPath(ConfigurationManager.AppSettings["SavePath"] + "/Temp/");
                    if (!Directory.Exists(tempFolder))
                    {
                        Directory.CreateDirectory(tempFolder);
                    }
                    using (ZipFile zip = ZipFile.Create(tempFolder + UserInfo.CurrentUser.ID + ".zip"))
                    {
                        zip.BeginUpdate();
                        foreach (var item in list)
                        {
                            string file = Server.MapPath(ConfigurationManager.AppSettings["SavePath"] + item.UploadFile);
                            if (!string.IsNullOrEmpty(item.UploadFile) && System.IO.File.Exists(file))
                            {
                                zip.Add(file);
                            }
                        }
                        zip.CommitUpdate();
                    }
                    return File(ConfigurationManager.AppSettings["SavePath"] + "/Temp/" + UserInfo.CurrentUser.ID + ".zip", "application/octet-stream", UserInfo.CurrentUser.ID + ".zip");
                }
            }
            return Content(ATools.OperateAlter("下载失败！", "/Achievement"));
        }

        public ActionResult AchievementAuditing(long id)
        {
            AchievementsProvider.Instance.AchievementAuditing(id, true);
            return Redirect("/Achievement");
        }
    }
}
